package com.doule.farmerassistant;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.http.AndroidHttpClient;
import android.util.Log;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

/**
 * download apk from server.
 * 
 * @author happy
 * 
 */
public final class LoadMessageTask {

    /**
     * 
     * @param context
     *            Context
     * @param token
//     *            Authentication token
     * @param msgId
     *            message id.
     */
    public LoadMessageTask(Context context, final String token,
            final String msgId) {
        mContext = context;
        mToken = token;
        mMsgId = msgId;
    }

    /**
     * Authentication token.
     */
    private String mToken;

    /**
     * Context.
     */
    private Context mContext;

    /**
     * Message server url.
     */
    private String mServerUrl;

    /**
     * Message id.
     */
    private String mMsgId;

    /**
     * Message table.
     */
    private ArrayList<String> mMsgs = new ArrayList<String>();

    /**
     * Convert string array to jsonArray string.
     * 
     * @param ids
     *            Message ids
     * @return jsonArray string
     */
    private String strings2JsonStr(final ArrayList<String> ids) {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < ids.size(); i++) {
            jsonArray.put(ids.get(i));
        }
        return jsonArray.toString();
    }

    /**
     * When message was read set it's tag.
     * 
     * @param ids
     *            Message ids
     * @return true if set read tag success, else false
     */
    private boolean setReadMsg(ArrayList<String> ids) {
        AndroidHttpClient client = AndroidHttpClient.newInstance("Android");

        try {

            String myIds = strings2JsonStr(ids);
            Log.e("setReadMsg", "ids: " + myIds);
            HttpEntity entity = new StringEntity(myIds);

            HttpPost request = new HttpPost(mServerUrl + "/setReadMsg");
            request.setHeader("Content-type", "application/json");
            request.setHeader("tk", mToken);
            request.setEntity(entity);

            HttpResponse resp = client.execute(request);
            Header head = resp.getFirstHeader("error");
            if (null != head) {
                String error = head.getValue();
                Log.e("setReadMsg", "setReadMsg error: " + error);
                return false;
            }

            // Log.e("LoadTask", "strResult: " + mTaskJSONStr);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
        return false;
    }

    /**
     * parser jsonString.
     * 
     * @param jsonStr
     *            jsonString
     */
    private void parseJson(final String jsonStr) {
        String str = jsonStr.replace("\\", "");
        str = str.substring(1, str.length() - 1);
        try {
            JSONArray jsonArray = new JSONArray(str);

            mMsgs.clear();
            ArrayList<String> ids = new ArrayList<String>();

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                Log.i("mytest", "notification  obj is :  " + obj);
                if (obj.has("id")) {
                    ids.add(String.valueOf(obj.getInt("id")));
                }

                if (obj.has("body")) {
                    String s = obj.getString("body");
                    Log.e("mytest", "notification is :  " + s);
                    mMsgs.add(s);
                    sendNotification(s);
                }
            }

            if (ids.size() > 0) {
                setReadMsg(ids);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * Show notification.
     * 
     * @param notify
     *            Notification content.
     */
    @SuppressWarnings("deprecation")
    private void sendNotification(final String notify) {
        NotificationManager nm = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Notification n = new Notification(R.drawable.ic_launcher, notify,
                System.currentTimeMillis());
        n.flags = Notification.FLAG_AUTO_CANCEL;

        Intent i = new Intent();
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent contentIntent = PendingIntent.getActivity(mContext,
                R.string.app_name, i, PendingIntent.FLAG_UPDATE_CURRENT);

        n.setLatestEventInfo(mContext, "Hello " + notify, notify + "...",
                contentIntent);
        nm.notify(R.string.app_name, n);
    }

    /**
     * Get message from server.
     * 
     * @return true get message success, else false.
     */
    private boolean loadMessage() {

        mServerUrl = DeathConfig.getServerUrl();
        if (mToken == null || mServerUrl == null) {
            return true;
        }

        Log.e("LoadMessageTask", "server url: " + mServerUrl);
        HttpPost request = new HttpPost(mServerUrl + "/loadMsg");
        request.setHeader("content-type", "application/octet-stream");
        request.setHeader("tk", mToken);
        request.setHeader("id", mMsgId);

        AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
        try {
            HttpResponse resp = client.execute(request);
            Header head = resp.getFirstHeader("error");
            if (null != head) {
                String error = head.getValue();
                Log.e("UserLoginTask", "login error: " + error);
                return false;
            }

            HttpEntity entity = resp.getEntity();
            String strResult = EntityUtils.toString(entity, "UTF-8");
            parseJson(strResult);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
        return false;
    }

    /**
     * Worker runnable object.
     */
    private final Runnable worker = new Runnable() {

        @Override
        public void run() {
            loadMessage();
        }
    };

    /**
     * Execute working thread.
     * 
     */
    public void go() {
        new Thread(worker).start();
    }
}
